<?php
class CiuexamsController extends AppController {

	var $name = 'Ciuexams';
	var $components = array(
        'Auth'=>array(
        'userModel' => 'Ciuuser',
        'loginError' => "Usuario/Clave equivocada",
        'loginRedirect' => array('controller' => 'ciuusers', 'action' => 'home'),
        'autoRedirect' => false, /* evita la redireccion inmediata y le deja el control al metodo local */
        'loginAction' => array(
                  'controller' => 'ciuusers',
                  'action' => 'login',
                  'plugin' => false,
                 'admin' => false,
		)
		)
		, 'Session'
	);
	
	var $uses=array('Ciuexam','Ciuacademicperiod');
	
	var $paginate = array(
        'limit' => 10,
        'order' => array(
            'Ciuexam.examination_date' => 'desc'
        )
    );
	
	function index($plan_id = null) {	
		$this->Ciuexam->recursive = 0;
		$period=$this->Ciuacademicperiod->getCurrent();
		$controller="Ciuexam";
		$conditions=array();
		$planData=array();
		if( $plan_id != null){
			$conditions[$controller . ".ciuplan_id"]= $plan_id;  //filtra por el plan dado
			$planData = $this->Ciuexam->Ciuplan->findById($plan_id);
		}
		$conditions[$controller . ".ciuacademicperiod_id"]= $period;  // Solo examenes del periodo academico actual
		$this->paginate[$controller]['conditions'] = $conditions;
		$peopleleft= $this->getPeopleToExam();
		$this->set('plan',$planData);
		$this->set('peopleleft',$peopleleft);
		$this->set('ciuexams', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid ciuexam', true));
			$this->redirect(array('action' => 'index'));
		}
		$takerids = $this->Ciuexam->CiuexamCiuuser->find('list',array('conditions'=>array('CiuexamCiuuser.ciuexam_id'=>$id ),'fields'=>array('CiuexamCiuuser.ciuuser_id')));
		$takers =   $this->Ciuexam->CiuexamCiuuser->Ciuuser->find('list', array('fields'=>array('id','name','document','ciuadmisionstate_id'), 'conditions'=>array('Ciuuser.id'=> $takerids  )));
		$states =   $this->Ciuexam->CiuexamCiuuser->Ciuuser->find('list', array('fields'=>array('id','ciuadmisionstate_id'), 'conditions'=>array('Ciuuser.id'=> $takerids  )));
		//$statedesc = $this->Ciu->find('list', array('fields'=>array('id','ciuadmisionstate_id'), 'conditions'=>array('Ciuuser.id'=> $takerids  )));
		$this->set('takers',$takers);
		$this->set('states',$states);
		$this->set('ciuexam', $this->Ciuexam->read(null, $id));
	}

	function add($plan_id = null) {
		if (!empty($this->data)) {    
			$this->Ciuexam->create();
			$period=$this->Ciuacademicperiod->getCurrent();
			$planData = $this->Ciuexam->Ciuplan->findById(  $this->data['Ciuexam']['ciuplan_id']);
			
			$this->data['Ciuexam']['name']=$planData['Ciuplan']['name'] ." - ".
			$this->data['Ciuexam']['examination_date']['year'].
			$this->data['Ciuexam']['examination_date']['month'].
			$this->data['Ciuexam']['examination_date']['day']
			;

			$this->data['Ciuexam']['ciuacademicperiod_id']=$period;
			if ($this->Ciuexam->save($this->data)) {
				$this->Session->setFlash(__('The ciuexam has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The ciuexam could not be saved. Please, try again.', true));
			}
		}
		$ciuplans = array();
		if($plan_id!=null){
            $ciuplans = $this->Ciuexam->Ciuplan->find('list',array('conditions'=>array('Ciuplan.id'=>$plan_id)));
		}else{
            $sql="Select distinct plan.id
			  from ciuplans plan
			  join ciusubjects subject on  plan.id=  subject.ciuplan_id
			  where plan.id <>5";  // que no trea el plan "Ninguno"
                
			$plansubjectraw=$this->Ciuexam->query($sql);
			$plan=array();
			foreach($plansubjectraw as $key => $row){
				$plan[]=$row["plan"]["id"];
			}
									 
			$ciuplans = $this->Ciuexam->Ciuplan->find('list',array('conditions'=>array('Ciuplan.id'=>$plan)));
		}

		$ciuexamstates = $this->Ciuexam->Ciuexamstate->find('list');
		$this->set(compact('ciuplans', 'ciuexamstates'));
	}
	
	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid ciuexam', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Ciuexam->save($this->data)) {
				$this->Session->setFlash(__('The ciuexam has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The ciuexam could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Ciuexam->read(null, $id);
		}
		$ciuplans = $this->Ciuexam->Ciuplan->find('list');
		$ciuexamstates = $this->Ciuexam->Ciuexamstate->find('list');
		$this->set(compact('ciuplans', 'ciuexamstates'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for ciuexam', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Ciuexam->delete($id)) {
			$this->Session->setFlash(__('Ciuexam deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Ciuexam was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
	
	//asigna estudiantes aspirantes a un examen
	function assign($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid ciuexam', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->data = $this->Ciuexam->read(null, $id);
		if (!empty($this->data)) {
			$capacity=$this->data['Ciuexam']['capacity'];
			if($capacity<1){
				$capacity=30;
			}
			$plan_id = $this->data['Ciuexam']['ciuplan_id'];
			
            //condicion de asignacion:
			$condicionAsignacion="verified=1 and ciuadmisionstate_id=1 and ciuplan_id=". $plan_id ." limit 0, $capacity ";
			
			$countsql="select count(*) as qty from ciuusers where " . $condicionAsignacion ;
			$result=$this->Ciuexam->query($countsql);
			$qty=$result[0][0]['qty'];	
			if($qty<1){
				$qty=0;
			}

            //Relaciona los aspirantes a un examen  
			$insert="insert into ciuexam_ciuusers(ciuexam_id,ciuuser_id,ciuadmisionstate_id) ".
			" select $id, id, 2 from ciuusers where ". $condicionAsignacion ;
			$this->Ciuexam->query($insert);
			
            //cuenta los aspirantes relacionados con un examen
			$countPeople="select count(*) as qty from ciuexam_ciuusers where ciuexam_id=" . $id ;
			$result=$this->Ciuexam->query($countPeople);
			$qty=$result[0][0]['qty'];	
			if($qty<1){
				$qty=0;
			}
			//cambia el numero de personas en el examen 
			$update="update ciuexams set people_count='". $qty. "' where id=$id";
			$this->Ciuexam->query($update);
			
			
			//cambia el estado a Con examen programado.
			$update="update ciuusers set ciuadmisionstate_id=2 where id in (select ciuuser_id from ciuexam_ciuusers where ciuexam_id=$id) ";
			$this->Ciuexam->query($update);
			$this->Session->setFlash($qty . " aspirantes asignados");
			
		}
		$this->redirect(array('action' => 'index'));
	}
	
	function sendmail($to="johana.rios@unillanos.edu.co", $subject="Test", $body="This is it", $bcc=array()){	
		$this->Email->from = "Idiomas Unillanos <institutodeidiomas@unillanos.edu.co>";
		$this->Email->to = $to;
		$this->Email->bcc=$bcc;
		$this->Email->subject = $subject;
		$this->Email->template = 'simple';
		$this->set('body', $body);
		$this->Email->delivery = 'smtp';
		$this->Email->send();
		$this->set('smtp_errors', $this->Email->smtpError);
		return $this->Email->smtpError;
	}
	
        //enviar un correo a los que tienen programado el examen. 
	function notify($id=null){
		if (!$id ) {
			$this->Session->setFlash(__('Invalid ciuexam', true));
			$this->redirect(array('action' => 'index'));
		}
		if (empty($this->data)) {
			$this->data = $this->Ciuexam->read(null, $id);
		}
		$list = array();
		//todos los registros para un exmen en particular.
		$raw=$this->Ciuexam->CiuexamCiuuser->find('all',array('conditions'=>array('Ciuexam.id'=>$id)));
		//se extraen los correos y se dejan en el arreglo list
		foreach($raw as $key => $val){
			if( $val['Ciuuser']['email']!="" && $val['Ciuuser']['email']!=null   ){
			$list[]=$val['Ciuuser']['email'];
			}
		}
		$to="institutodeidiomas@unillanos.edu.co";
		$subject="Invitación a Examen de clasificación. Centro de Idiomas";
		$body="Favor presentarse el examen de clasificacacion  en:\n\n"
		." Fecha: " . $this->data['Ciuexam']['examination_date']
		."\n". " Lugar: " . $this->data['Ciuexam']['location']
                ."\n Cualquier inconveniente dirigirse a la oficina del Centro de Idiomas "
		; 
		//se envia un solo correo  con copia oculta a todos los correos de los llamados al examen.
		$bcc=$list;
		$result= $this->sendmail( $to, $subject, $body, $bcc);
		$this->set('smtp_errors', $result);
		$this->Session->setFlash(__('Aspirantes notificados via email', true));	
		$this->redirect(array('action' => 'index'));
	}
	function getPeopleToExam(){
		$countsql="select count(*) as qty from ciuusers where ciuadmisionstate_id=1 and verified=1";
		$countleft = $this->Ciuexam->query($countsql);
		return $countleft[0][0]['qty'];
	}
}
